package org.ezplatform.office.questionnaire.web.rest;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.ezplatform.cloud.api.component.attachment.AttachmentUtilsService;
import org.ezplatform.component.check.annotation.DataCheck;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.exception.ValidationException;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.controller.BaseController;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.office.questionnaire.entity.Questionnaire;
import org.ezplatform.office.questionnaire.entity.QuestionnaireAnswer;
import org.ezplatform.office.questionnaire.entity.QuestionnaireTopic;
import org.ezplatform.office.questionnaire.entity.QuestionnaireTopicOptions;
import org.ezplatform.office.questionnaire.service.QuestionnaireAnswerService;
import org.ezplatform.office.questionnaire.service.QuestionnaireAnswerStatusService;
import org.ezplatform.office.questionnaire.service.QuestionnaireService;
import org.ezplatform.office.questionnaire.service.QuestionnaireSetService;
import org.ezplatform.office.questionnaire.service.QuestionnaireTopicOptionsService;
import org.ezplatform.office.questionnaire.service.QuestionnaireTopicService;
import org.ezplatform.util.GlobalConstant;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

@RestController
@RequestMapping(value = "/api/w/questionnaire/questionnaire/topic")
public class QuestionnaireTopicWebApiController extends BaseController<QuestionnaireTopic, String>{
	
	private final static Logger logger = LoggerFactory.getLogger(QuestionnaireTopicWebApiController.class);
	@Autowired
	private QuestionnaireTopicService topicService;
	
	@Autowired
	private QuestionnaireTopicOptionsService optionService;
	
	@Autowired
	private AttachmentUtilsService attachmentUtilsService;

	@Autowired
	private QuestionnaireService questionnaireService;

	@Autowired
	private QuestionnaireAnswerService answerService;

	@Autowired
	private QuestionnaireAnswerStatusService questionnaireAnswerStatusService;
	
	@Autowired
	private QuestionnaireSetService questionnaireSetService;
	
	@Override
	protected BaseService<QuestionnaireTopic, String> getEntityService() {
		return topicService;
	}
	
	/**
     * 查询问卷题目
     * @param entity
     * @param model
     * @return
     */
	@RequestMapping(value = "/getDesign")
    @ResponseBody
    public OperationResult getDesign(HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		String quesitionnaireId = request.getParameter("quesitionnaireId");
		if(quesitionnaireId != null && !ValidateUtils.validateId(quesitionnaireId)) {
            throw new ValidationException("非法参数");
        }
		Map<String, Object> map = new HashMap<>();

		String userId = WebUtils.getCurrentUser().getUserId();
		List<QuestionnaireTopic> list = topicService.getTopicOPtionInfo(quesitionnaireId,userId,user.getJwtToken(),false);
		//Lambda表达式 查询所有分页页数
		List<String> pageList = list.stream().map((topic)->{
			if(StringUtils.equals(topic.getTopicType(),"paging")){
				return topic.getPage();
			}else{
				return null;
			}
		}).collect(Collectors.toList());
		if (CollectionUtils.isNotEmpty(list)) {
			int index = 0;
			for (int i = 0; i < list.size(); i++) {
				QuestionnaireTopic questionnaireTopic = list.get(i);
				String topicType = questionnaireTopic.getTopicType();
				if (!"paging".equals(topicType) && !"illustrate".equals(topicType)) {
					index++;
				}
				questionnaireTopic.setTopicNo(String.valueOf(index));
			}
		}
		map.put("topicSetting", list);
		if(CollectionUtils.isNotEmpty(pageList)){
			pageList.removeAll(Collections.singleton(null));
			if(pageList.size() == 0){
				map.put("page",0);
			}else{
				map.put("page",pageList.size());
			}
		}else{
			map.put("page",0);
		}
		/*
		 * 获取附件id
		 */
		if(list != null && list.size() > 0) {
			for (QuestionnaireTopic questionnaireTopic : list) {
				if(questionnaireTopic.getList() != null && questionnaireTopic.getList().size() > 0) {
					for(int j=0;j<questionnaireTopic.getList().size();j++){
						QuestionnaireTopicOptions option = questionnaireTopic.getList().get(j);
						String jsonVal = option.getOptionSetting();
						QuestionnaireAnswer answer = option.getAnswer();
						if(StringUtils.isNotEmpty(jsonVal) && !jsonVal.contains("option-option")) {
							JSONObject jsStr = JSONObject.parseObject(jsonVal);
							if( !"".equals(jsStr.getString("optionImg")) && jsStr.getString("optionImg") != null) {
								String fileInfo =attachmentUtilsService.getAttachmentInfo(jsStr.getString("optionImg"),user.getJwtToken());
							    answer.setAttachment("["+fileInfo+"]");
							    List<Map<String, String>> fileInfoList =attachmentUtilsService.getAttachmentByIds(jsStr.getString("optionImg"), WebUtils.getCurrentUser().getCorpId(), user.getJwtToken());
								String url = "/attachment/image?fid="+jsStr.getString("optionImg")+"&chksum="+fileInfoList.get(0).get("checksum")+"&verifier="+userId;
							    answer.setUrlPic(url);
								option.setAnswer(answer);
							}
						}
					}
				}
			}
		}
    	Questionnaire oq = questionnaireService.findOne(quesitionnaireId);
    	String titleSetting = StringUtils.null2String(oq.getTitleSetting());
    	if(!"".equals(titleSetting)){
    		Map<String, Object> mapSetting = new HashMap<String, Object>();
    		mapSetting = JsonUtils.readValue(titleSetting.replaceAll("\r\n|\r|\n", ""));
    		map.put("titleSetting", mapSetting);
    	}else{
    		map.put("titleSetting", titleSetting);
    	}
    	map.put("entity", oq);
    	map.put("flexServerPath", GlobalConstant.getFlexServerPath(request));
    	List<Map> setList = this.questionnaireSetService.getQuesSetListByQuesId(quesitionnaireId);
    	map.put("setListCount", setList.size());
		return OperationResult.buildSuccessResult(map);
	}
	
	/**
     * 保存问卷题目
     * @param entity
     * @param model
     * @return
     */
    @RequestMapping(value = "/designEdit", method = RequestMethod.POST)
    @ResponseBody
    @DataCheck(paramKey="quesitionnaireId", dataTable="oa_questionnaire", dataField="id", extraCondi={"publish=0"})
    public OperationResult designEdit(HttpServletRequest request) {
    	Map i18nKey=new HashMap(1);
    	List<QuestionnaireTopic> listTopic = new ArrayList<QuestionnaireTopic>();
    	List<QuestionnaireTopicOptions> listOptions = new ArrayList<QuestionnaireTopicOptions>();
    	String isImport = request.getParameter("isImport");
    	if(isImport != null && !ValidateUtils.validateId(isImport)) {
            throw new ValidationException("非法参数");
        }
    	String quesitionnaireId = request.getParameter("quesitionnaireId");
    	if(quesitionnaireId != null && !ValidateUtils.validateId(quesitionnaireId)) {
            throw new ValidationException("非法参数");
        }
    	String[] sinselect = request.getParameterValues("sinselect");
    	if(sinselect != null && !ValidateUtils.validateId(sinselect)) {
            throw new ValidationException("非法参数");
        }
    	String[] trueOrFalse = request.getParameterValues("trueOrFalse");
    	if(trueOrFalse != null && !ValidateUtils.validateId(trueOrFalse)) {
            throw new ValidationException("非法参数");
        }
    	String[] multiselect = request.getParameterValues("multiselect");
    	if(multiselect != null && !ValidateUtils.validateId(multiselect)) {
            throw new ValidationException("非法参数");
        }
    	String[] check = request.getParameterValues("check");
    	if(check != null && !ValidateUtils.validateId(check)) {
            throw new ValidationException("非法参数");
        }
    	String[] fillInBlanks = request.getParameterValues("fillInBlanks");
    	if(fillInBlanks != null && !ValidateUtils.validateId(fillInBlanks)) {
            throw new ValidationException("非法参数");
        }
    	String[] answer = request.getParameterValues("answer");
    	if(answer != null && !ValidateUtils.validateId(answer)) {
            throw new ValidationException("非法参数");
        }
    	String[] shortAnswer = request.getParameterValues("shortAnswer");
    	if(shortAnswer != null && !ValidateUtils.validateId(shortAnswer)) {
            throw new ValidationException("非法参数");
        }
    	String[] field = request.getParameterValues("field");
    	if(field != null && !ValidateUtils.validateId(field)) {
            throw new ValidationException("非法参数");
        }
    	String[] scale = request.getParameterValues("scale");
    	if(scale != null && !ValidateUtils.validateId(scale)) {
            throw new ValidationException("非法参数");
        }
    	String[] mulscale = request.getParameterValues("mulscale");
    	if(mulscale != null && !ValidateUtils.validateId(mulscale)) {
            throw new ValidationException("非法参数");
        }
    	String[] illustrate = request.getParameterValues("illustrate");
    	if(illustrate != null && !ValidateUtils.validateId(illustrate)) {
            throw new ValidationException("非法参数");
        }
    	String[] paging = request.getParameterValues("paging");
    	if(paging != null && !ValidateUtils.validateId(paging)) {
            throw new ValidationException("非法参数");
        }
    	if(sinselect != null && sinselect.length>0){
    		for(int i=0;i<sinselect.length;i++){
    			String times = sinselect[i];
    			String topicAllSetting = request.getParameter(times+"sinselect");
    			String optionSetting =request.getParameter(times+"option");
    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting.replaceAll("\r\n|\r|\n", ""));
    			QuestionnaireTopic topic = new QuestionnaireTopic();
    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "sinselect");
    			listTopic.add(topic);
    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
    			listOptions.addAll(listOption);
    		}
    	} 
        if(trueOrFalse != null && trueOrFalse.length>0){
    		for(int i=0;i<trueOrFalse.length;i++){
    			String times = trueOrFalse[i];
    			String topicAllSetting = request.getParameter(times+"trueOrFalse");
    			String optionSetting =request.getParameter(times+"option");
    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting.replaceAll("\r\n|\r|\n", ""));
    			QuestionnaireTopic topic = new QuestionnaireTopic();
    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "trueOrFalse");
    			listTopic.add(topic);
    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
    			listOptions.addAll(listOption);
    		}
    	}
    	if(multiselect !=null && multiselect.length>0){
    		for(int i=0;i<multiselect.length;i++){
    			String times = multiselect[i];
    			String topicAllSetting = request.getParameter(times+"multiselect");
    			String optionSetting =request.getParameter(times+"option");
    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting.replaceAll("\r\n|\r|\n", ""));
    			QuestionnaireTopic topic = new QuestionnaireTopic();
    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "multiselect");
    			listTopic.add(topic);
    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
    			listOptions.addAll(listOption);
    		}
    	} 
    	if(check != null && check.length>0){
    		for(int i=0;i<check.length;i++){
    			String times = check[i];
    			String topicAllSetting = request.getParameter(times+"check");
    			String optionSetting =request.getParameter(times+"option");
    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting.replaceAll("\r\n|\r|\n", ""));
    			QuestionnaireTopic topic = new QuestionnaireTopic();
    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "check");
    			listTopic.add(topic);
    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
    			listOptions.addAll(listOption);
    		}
    	} 
    	if(fillInBlanks !=null && fillInBlanks.length>0){
    		for(int i=0;i<fillInBlanks.length;i++){
    			String times = fillInBlanks[i];
    			String topicAllSetting = request.getParameter(times+"fillInBlanks");
    			String optionSetting =request.getParameter(times+"option");
    			Map<String,Object> map = JSONObject.parseObject(topicAllSetting);
    			QuestionnaireTopic topic = new QuestionnaireTopic();
    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "fillInBlanks");
    			listTopic.add(topic);
    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
    			listOptions.addAll(listOption);
    		}
    	} 
    	if(shortAnswer !=null && shortAnswer.length>0){
    		for(int i=0;i<shortAnswer.length;i++){
    			String times = shortAnswer[i];
    			String topicAllSetting = request.getParameter(times+"shortAnswer");
    			String optionSetting =request.getParameter(times+"option");
    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting.replaceAll("\r\n|\r|\n", ""));
    			QuestionnaireTopic topic = new QuestionnaireTopic();
    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "shortAnswer");
    			listTopic.add(topic);
    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
    			listOptions.addAll(listOption);
    		}
    	} 
    	if(answer !=null && answer.length>0){
    		for(int i=0;i<answer.length;i++){
    			String times = answer[i];
    			String topicAllSetting = request.getParameter(times+"answer");
    			String optionSetting =request.getParameter(times+"option");
    			Map<String,Object> map = JSONObject.parseObject(topicAllSetting);
    			QuestionnaireTopic topic = new QuestionnaireTopic();
    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "answer");
    			listTopic.add(topic);
    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
    			listOptions.addAll(listOption);
    		}
    	} 
    	if(field !=null && field.length>0){
    		for(int i=0;i<field.length;i++){
    			String times = field[i];
    			String topicAllSetting = request.getParameter(times+"field");
    			String optionSetting =request.getParameter(times+"option");
    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting.replaceAll("\r\n|\r|\n", ""));
    			QuestionnaireTopic topic = new QuestionnaireTopic();
    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "field");
    			listTopic.add(topic);
    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
    			listOptions.addAll(listOption);
    		}
    	} 
    	if(scale !=null && scale.length>0){
    		for(int i=0;i<scale.length;i++){
    			String times = scale[i];
    			String topicAllSetting = request.getParameter(times+"scale");
    			String optionSetting =request.getParameter(times+"option");
    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting.replaceAll("\r\n|\r|\n", ""));
    			QuestionnaireTopic topic = new QuestionnaireTopic();
    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "scale");
    			listTopic.add(topic);
    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting, topic.getId());
    			listOptions.addAll(listOption);
    		}
    	} 
    	if(mulscale != null && mulscale.length>0){
    		for(int i=0;i<mulscale.length;i++){
    			String times = mulscale[i];
    			String topicAllSetting = request.getParameter(times+"mulscale");
    			String optionSetting =request.getParameter(times+"option");
    			String optionChildSetting  =request.getParameter(times+"childoption");
    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting.replaceAll("\r\n|\r|\n", ""));
    			QuestionnaireTopic topic = new QuestionnaireTopic();
    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "mulscale");
    			listTopic.add(topic);
    			List<QuestionnaireTopicOptions> listOption = optionService.getSaveOptionsInfo(optionSetting,optionChildSetting, topic.getId());
    			listOptions.addAll(listOption);
    		}
    	} 
    	if(illustrate !=null && illustrate.length>0){
    		for(int i=0;i<illustrate.length;i++){
    			String times = illustrate[i];
    			String topicAllSetting = request.getParameter(times+"illustrate");
    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting.replaceAll("\r\n|\r|\n", ""));
    			QuestionnaireTopic topic = new QuestionnaireTopic();
    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "illustrate");
    			listTopic.add(topic);
    		}
    	}
    	if(paging !=null && paging.length>0){
    		for(int i=0;i<paging.length;i++){
    			String times = paging[i];
    			String topicAllSetting = request.getParameter(times+"paging");
    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting.replaceAll("\r\n|\r|\n", ""));
    			QuestionnaireTopic topic = new QuestionnaireTopic();
    			topic = topicService.getSaveTopicInfo(map, quesitionnaireId, "paging");
    			topic.setTopicSetting("{\"page\":\""+(i+1)+"\",\"herePage\":\"" + map.get("herePage") + "\",\"totalPages\":\"" + map.get("totalPages") + "\"}");
    			listTopic.add(topic);
    		}
    	}
    	Questionnaire entity = questionnaireService.findOne(quesitionnaireId);
    	if(entity != null) {
    		String sumScore = ValidateUtils.filter(request.getParameter("sumScore"));
    		String sumTopicNum = ValidateUtils.filter(request.getParameter("sumTopicNum"));
    		if(StringUtils.isBlank(isImport)) {
    			entity.setSumScore(sumScore);
        		entity.setSumTopicNum(sumTopicNum);
    		}else if(StringUtils.isNotBlank(entity.getSumScore())&&StringUtils.isNotBlank(entity.getSumTopicNum())){
    			entity.setSumScore(String.valueOf(Long.valueOf(entity.getSumScore())+Long.valueOf(sumScore)));
    			entity.setSumTopicNum(String.valueOf(Long.valueOf(entity.getSumTopicNum())+Long.valueOf(sumTopicNum)));
    		}
    		questionnaireService.save(entity);
    		List<String> topicList = topicService.getTopicIdByQeusId(quesitionnaireId);
        	if(topicList != null && topicList.size()>0){
        		if(StringUtils.isBlank(isImport)) {
        			optionService.deleteOptionsByTopicId(topicList);
        		}
        	}
        	if(StringUtils.isBlank(isImport)) {
        		topicService.deleteTopicByQuesId(quesitionnaireId);
        	}
        	List<String> queIdsList = new ArrayList<>();
        	queIdsList.add(quesitionnaireId);
    		answerService.deleteAnswerByQuesId(queIdsList);
    		questionnaireAnswerStatusService.deleteStatusByQuesId(queIdsList);
    		topicService.save(listTopic);
        	optionService.save(listOptions);
    		questionnaireService.setQuesSendN(quesitionnaireId);
    		questionnaireService.updateQuesMobile(quesitionnaireId,"","0");
        	String clickBtnType = request.getParameter("clickBtnType");
        	if("preview".equals(clickBtnType)) {
        		Map<String, Boolean> map = new HashMap<String, Boolean>();
            	map.put("noMessageBox", true);
        		return OperationResult.buildSuccessResult(map);
        	}
        	i18nKey.put("i18NCode", "oa.que.savesuccess");
        	return OperationResult.buildSuccessResult("保存成功",i18nKey);
    	}else {
    		i18nKey.put("i18NCode", "oa.que.curranswerdeleted");
    		return OperationResult.buildFailureResult("该问卷已删除",i18nKey);
    	}
    }

	/**
	 *  检查问卷是否有被答过
	 * @return      true 已经有人答题了
	 */
	@GetMapping("/chechQues")
	@ResponseBody
    public OperationResult chechQues(HttpServletRequest request){
		//问卷id
		String quesitionnaireId = request.getParameter("quesitionnaireId");
		if(quesitionnaireId != null && !ValidateUtils.validateId(quesitionnaireId)) {
            throw new ValidationException("非法参数");
        }
		Questionnaire entity = this.questionnaireService.findOne(quesitionnaireId);
		if(entity == null) return OperationResult.buildSuccessResult("notExist");
		List<QuestionnaireAnswer> answerList = answerService.getAnswerByQuesId(quesitionnaireId);
		boolean flag = false;
		if(CollectionUtils.isNotEmpty(answerList)){
			flag = true;
		}
    	return OperationResult.buildSuccessResult("查询成功",flag);
	}

	/**
     * 保存问卷题目
     * @param entity
     * @param model
     * @return
     */
    @RequestMapping(value = "/clearAnswer", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult clearAnswer(HttpServletRequest request) {
    	Map i18nKey=new HashMap(1);
    	try {
			//问卷id
			String quesitionnaireId = ValidateUtils.filter(request.getParameter("quesitionnaireId"));
			Questionnaire entity = questionnaireService.findOne(quesitionnaireId);
			if(entity != null) {
				List<String> queIdsList = new ArrayList<>();
				queIdsList.add(quesitionnaireId);
				answerService.deleteAnswerByQuesId(queIdsList);
				questionnaireAnswerStatusService.deleteStatusByQuesId(queIdsList);
				questionnaireService.setQuesSendN(quesitionnaireId);
				questionnaireService.updateQuesMobile(quesitionnaireId,"","0");
				i18nKey.put("i18NCode", "oa.que.deletedsuccess");
				return OperationResult.buildSuccessResult("清除成功",i18nKey);
			}else {
				i18nKey.put("i18NCode", "oa.que.curranswerdeleted");
				return OperationResult.buildFailureResult("该问卷已删除",i18nKey);
			}
		} catch (Exception e) {
			e.printStackTrace();
			i18nKey.put("i18NCode", "oa.que.deletedfailure");
			return OperationResult.buildFailureResult("清除失败",i18nKey);
		}
    }
    
	/**
	 * 删除题目
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/deleteTopicById", method = RequestMethod.POST)
	@ResponseBody
	public OperationResult deleteTopicById(HttpServletRequest request) {
		Map i18nKey=new HashMap(1);
		try {
			String topicId = ValidateUtils.filter(request.getParameter("topicId"));
			String topicScore = ValidateUtils.filter(request.getParameter("topicScore"));
			String quesitionnaireId = ValidateUtils.filter(request.getParameter("quesitionnaireId"));
			List<String> topicIdList = new ArrayList<>();
			topicIdList.add(topicId);
			if (this.optionService.deleteOptionsByTopicId(topicIdList)) {
				this.topicService.deleteTopicById(topicId);
				Questionnaire questionnaire = this.questionnaireService.findOne(quesitionnaireId);
				String sumScoreOld = questionnaire.getSumScore();
				String sumTopicNumOld = questionnaire.getSumTopicNum();
				questionnaire.setSumScore(String.valueOf(Float.parseFloat(sumScoreOld) - Float.parseFloat(topicScore)));
				questionnaire.setSumTopicNum(String.valueOf(Integer.parseInt(sumTopicNumOld) - 1));
				this.questionnaireService.save(questionnaire);
			}
			i18nKey.put("i18NCode", "oa.que.deletesuccessful");
			return OperationResult.buildSuccessResult("删除成功",i18nKey);
		} catch (Exception e) {
			i18nKey.put("i18NCode", "oa.que.deletefailture");
			return OperationResult.buildFailureResult("删除失败",i18nKey);
		}
	}
	
	/**
	 * excel导入题目(xlsx)
	 * @param request
	 * @throws Exception 
	 */
	@SuppressWarnings("resource")
	@RequestMapping(value="/importTopic",method=RequestMethod.POST)
	public OperationResult importTopics( HttpServletRequest request,@RequestPart("topicFile") MultipartFile topicFile,@RequestParam("questionnaireId") String questionnaireId ) {
		Map<String,Object>i18nKey=new HashMap<>(1);
		try {
			XSSFWorkbook workbook=new XSSFWorkbook(topicFile.getInputStream());
			OperationResult result=null;
			Questionnaire entity = questionnaireService.findOne(questionnaireId);
			XSSFSheet sheet=workbook.getSheetAt(0);
			if("questionnaireSurvey".equals(entity.getType())) {
				result=topicService.resolveSheet(sheet, "0", questionnaireId);	
			}else if("questionnaireVote".equals(entity.getType())) {
				result=topicService.resolveSheet(sheet, "1", questionnaireId);	
			}else if("questionnaireExam".equals(entity.getType())) {
				result=topicService.resolveSheet(sheet, "2", questionnaireId);	
			}
			if(result!=null) {
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("解析导入题目出错", e);
			i18nKey.put("i18NCode","oa.que.savefailure");
			return OperationResult.buildFailureResult("保存失败",i18nKey);
		}
		i18nKey.put("i18NCode", "oa.que.savesuccess");
    	return OperationResult.buildSuccessResult("保存成功",i18nKey);
		 
	}
	
	/**
	 * 题目导入模板下载
	 * @param request
	 * @param response
	 * @param type
	 * @return
	 */
	@RequestMapping("/download/{type}")
	public OperationResult downloadFile(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("type") String type) {
		String fileName = "";
		Map<String, Object> i18nKey = new HashMap<>(1);
		if ("0".equals(type)) {// 调查
			fileName = "调查.xlsx";
		} else if ("1".equals(type)) {// 投票
			fileName = "投票.xlsx";
		} else if ("2".equals(type)) {// 考试
			fileName = "考试.xlsx";
		}
		try {
			String filePath = request.getSession().getServletContext()
					.getRealPath("/web/dist/modules/questionnaire/downloadfile");
			ServletOutputStream outputStream = response.getOutputStream();
			byte[] bytes = FileUtils.readFileToByteArray(new File(filePath+"/"+fileName));
			fileName = URLEncoder.encode(fileName, "utf-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			outputStream.write(bytes);
			outputStream.flush();
			outputStream.close();
		} catch (IOException e) {
			logger.error("问卷模板下载失败", e);
			e.printStackTrace();
			return OperationResult.buildFailureResult("下载失败");
		}
		i18nKey.put("i18NCode", "oa.que.savesuccess");
		return OperationResult.buildSuccessResult("下载成功", i18nKey);
	}
}